//
//  ECUIView_CourseList.m
//  Edu_iOS2018
//
//  Created by yanyan on 2018/1/26.
//  Copyright © 2018年 yanyan. All rights reserved.
//
#import "CYUITVDSD_base.h"
#import "CYUITVDSDBridge.h"
#import "ECUIView_ListHeader.h"
#import "ECUITVCell_CourseList.h"
#import "ECUIView_Category.h"
#import "ECUIVC_CourseDetail.h"
#import "ECUIView_CourseList.h"
@interface ECUIView_CourseList()<DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
@property(nonatomic,strong)ECUIView_ListHeader *header;
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) CYUITVDSD_base *dsd;
@property(nonatomic,strong)ECUIView_Category *categoryView;
@property(nonatomic,strong)NSDictionary *condition;
@property(nonatomic,strong)NSMutableArray *dataSource;
@property(nonatomic,strong)NSURLSessionDataTask *task;
@end
@implementation ECUIView_CourseList

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)addSubviews
{
    [super addSubviews];
    WeakSelf(weakSelf);
    _header = [[ECUIView_ListHeader alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 41)];
    if (self.selectCategory) {
        [_header setSelectCategory:self.selectCategory];
    }
    _header.block_categoryBtn = ^(id obj) {
        [weakSelf.tableView setContentOffset:CGPointZero animated:NO];
        [weakSelf action_categoryBtn:obj];
    };
    _header.block_selectedSort = ^(id obj) {
        [weakSelf resignKeyBoard];
        [weakSelf showCategoryView:NO];
        weakSelf.condition = obj;
        weakSelf.start = 0;
        [weakSelf.tableView setContentOffset:CGPointZero animated:NO];
        [weakSelf requestData];
    };
    [self addSubview:_header];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_header.frame), kScreenWidth, CGRectGetHeight(self.bounds)-CGRectGetMaxY(_header.frame))];
    _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _tableView.rowHeight = kProportion_Height(258);
    _tableView.emptyDataSetDelegate = self;
    _tableView.emptyDataSetSource = self;
    _tableView.tableFooterView = [UIView new];
    _tableView.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
        [weakSelf resignKeyBoard];
        [weakSelf refreshHeaderForCourseList];
    }];
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf resignKeyBoard];
        [weakSelf requestData];
    }];
    _tableView.mj_footer = footer;
    _dsd = [[CYUITVDSD_base alloc]init];
    _dsd.classesIdbyReusedCells = @{@"cell":@"ECUITVCell_CourseList"};
    _dsd.block_itemSelected = ^(id obj) {
        [weakSelf showCourseDetail:obj];
    };
    _dsd.hasSelectedStyle = NO;
    [CYUITVDSDBridge bridge:_tableView dsd:_dsd];
    [self addSubview:_tableView];
 
}
-(void)refreshHeaderForCourseList
{
    self.start = 0;
    [self requestData];
}
- (void)showCourseDetail:(id)obj
{
    ECUIVC_CourseDetail* uivc_detail = [[ECUIVC_CourseDetail alloc]init];
    uivc_detail.hidesBottomBarWhenPushed = YES;
    uivc_detail.object = obj;
    UINavigationController *nav = ((UITabBarController*)[UIApplication sharedApplication].keyWindow.rootViewController).selectedViewController;
    [nav pushViewController:uivc_detail animated:YES];

}
- (void)setKeyName:(NSString *)keyName
{
    _keyName = keyName;
    DLog(@"请确保参数 SelectCategory，categorysData设置在keyName之前")
    [self requestData];
}
- (void)keyNameChanged:(NSString *)key
{
    _keyName = key;
}
- (void)setSelectCategory:(PrimaryCategoryModel *)selectCategory
{
    _selectCategory = selectCategory;
    [_header setSelectCategory:selectCategory];
    if (_categoryView) {
        _categoryView.defaultCategoryModel = _selectCategory;
    }
    
}
- (void)resignKeyBoard{
    if (self.block_resign) {
        self.block_resign(nil);
    }
}
-(void)action_categoryBtn:(id)sender
{
    [self resignKeyBoard];
    KHButtonState selectedState = ((ECUIButton_Category *)sender).selectedState;
    switch (selectedState) {
        case KHButtonStateNormal:
            break;
        case KHButtonStateSortDown:
        {
            _start = 0;
            [self showCategoryView:NO];
        }
            break;
        case KHButtonStateSortUp:
        {
            [self showCategoryView:YES];
        }
            break;
        default:
            break;
    }
    
}
-(void)showCategoryView:(BOOL)flag{
    if (flag) {
        [self addSubview:self.categoryView];
        if (self.categorysData) {
            if (self.selectCategory && !_categoryView.defaultCategoryModel) {
                _categoryView.defaultCategoryModel = self.selectCategory;
            }
            if (!_categoryView.categorysData) {
                _categoryView.categorysData = self.categorysData;
            }
          
        } else {
            [self requestCategoryData];
        }
        [self addSubview:self.categoryView];

        [UIView animateWithDuration:0.25 animations:^{
            self.categoryView.frame = CGRectMake(0, CGRectGetMaxY(_header.frame), kScreenWidth,self.bounds.size.height - CGRectGetMaxY(_header.frame));
        }];
    } else {
        if (_categoryView) {
            [self.categoryView removeFromSuperview];
            [UIView animateWithDuration:0.25 animations:^{
                self.categoryView.frame = CGRectMake(0, CGRectGetMaxY(_header.frame), kScreenWidth,0);
            }];
        }
        
    }
    
}
- (ECUIView_Category *)categoryView
{
    if (!_categoryView) {
        _categoryView = [[ECUIView_Category alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_header.frame), kScreenWidth,self.bounds.size.height - kNavHeight - CGRectGetMaxY(_header.frame))];
        _categoryView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        WeakSelf(weakSelf);
        _categoryView.block_selectedAtIndex = ^(id obj, NSIndexPath *indexPath) {
            [weakSelf showHeaderForSelectCategory:obj];
            [weakSelf requestCoursesWithCondition:obj];
        };
        
    }
    return _categoryView;
}
// 从搜索页进来 没有分类
-(void)requestCategoryData
{
    DLog(@"请求分类数据");
        WeakSelf(weakSelf);
        [HWHttpTool get:URL_AllCategory params:@{} success:^(id json) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
                weakSelf.categorysData = [ECModelData arrayForCategory:json];
                weakSelf.categoryView.categorysData = [ECModelData arrayForCategory:json];
                if (weakSelf.selectCategory) {
                    weakSelf.categoryView.defaultCategoryModel = self.selectCategory;

                }

            });
        } failure:^(NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
            });

        }];
}
-(void)showHeaderForSelectCategory:(PrimaryCategoryModel *)mo
{
  [self resignKeyBoard];
    self.start = 0;

    // 这里也需要判断一下全部与上一级的关系。
    PrimaryCategoryModel *defaultSelectMo = _categoryView.secondCategoryModel ? _categoryView.secondCategoryModel:_categoryView.firstCategoryModel;
    if ([mo.modelId isEqualToString: defaultSelectMo.modelId]) {
        mo = defaultSelectMo;
    }
    self.selectCategory = mo;
    _header.allCategoryBtn.selectedState = KHButtonStateSortDown;
    
    [_header setSelectCategory:self.selectCategory];
    
}
-(void)requestCoursesWithCondition:(id)obj
{
    [self showCategoryView:NO];
    [self requestData];
    
}


-(void)requestData{
    WeakSelf(weakSelf);
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (self.task && self.task.state != NSURLSessionTaskStateCompleted) {
        [self.task cancel];
    }
    if (self.selectCategory) {
        PrimaryCategoryModel *mo = self.selectCategory;
        DLog(@"对分类进行筛选----%@---id:%@",mo.title,mo.modelId);
        if (mo.modelId && mo.modelId.length > 0) {
            [params setValuesForKeysWithDictionary:@{@"categoryId":mo.modelId}];
        }
    }
    if (self.condition) {
        [params setValuesForKeysWithDictionary:self.condition];
    }
    if (self.keyName && self.keyName.length > 0) {
        [params setValue:self.keyName forKey:@"q"];
    }
    [params setValue:@(self.start) forKey:@"start"];
    DLog(@"对分类进行筛选-------%@",params);

    [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication] keyWindow] animated:YES];
  self.task = [HWHttpTool get:URL_CourseOfCategory params:params success:^(id json) {
      id data = [json valueForKey:@"data"];
      if (weakSelf.start == 0) {
          [self.dataSource removeAllObjects];
          [self.dataSource addObjectsFromArray:[ECModelData arrayForCourses:[data valueForKey:@"resources"]]];
      } else {
          [self.dataSource addObjectsFromArray:[ECModelData arrayForCourses:[data valueForKey:@"resources"]]];
      }
      weakSelf.start = self.dataSource.count;
        weakSelf.dsd.object = @{kTableCellDataSourceId:@[self.dataSource]};
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [weakSelf closeRefreshHeaderAndFooter:[[data valueForKey:@"total"] integerValue]];
            [weakSelf.tableView reloadData];
        });
      
    } failure:^(NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showWarnMessage:@"请求失败"];
            [weakSelf closeRefreshHeaderAndFooter:0];
        });
     

    }];
    
}
- (void)closeRefreshHeaderAndFooter:(NSInteger)total
{
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    if (total <= self.dataSource.count) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer resetNoMoreData];

    }
}
- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
#pragma mark - 空数据处理的情况 -
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"image_search_nodata"];
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
{
    NSString *tips;
    if (self.keyName) {
        tips = @"暂无符合条件的课程，【换个搜索关键词】试试吧";
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:tips];
        [attrStr addAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#b3b3b3"],NSFontAttributeName:[UIFont systemFontOfSize:14]} range:NSMakeRange(0,10)];

        [attrStr addAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FF6800"],NSFontAttributeName:[UIFont systemFontOfSize:14]} range:NSMakeRange(10,9)];
        [attrStr addAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#b3b3b3"],NSFontAttributeName:[UIFont systemFontOfSize:14]} range:NSMakeRange(19,3)];

        
        return attrStr;
        } else {
            tips = @"暂无相关课程，您可以【查看其他课程】";
            NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:tips];
            [attrStr addAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#b3b3b3"],NSFontAttributeName:[UIFont systemFontOfSize:16]} range:NSMakeRange(0,10)];
            [attrStr addAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FF6800"],NSFontAttributeName:[UIFont systemFontOfSize:16]} range:NSMakeRange(10,8)];
            
            return attrStr;

        }
    
    
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button
{
    if (self.keyName) {
        
    } else {
        // 查看其他分类
        [self showCategoryView:YES];
    }
}

@end
